<?php

namespace App\Http\Controllers;

use App\Models\Report;
use App\Services\AdminService;
use App\Services\ReportService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminController extends Controller
{
    public function __construct(
        private ReportService $reportService,
        private AdminService $adminService
    ) {
        // 只允许管理员访问
        $this->middleware(function ($request, $next) {
            if (! $request->user() || ! $request->user()->isAdmin()) {
                abort(403, '您无权访问此页面');
            }

            return $next($request);
        });
    }

    /**
     * 举报列表（管理员）
     */
    public function reports(Request $request): Response
    {
        $status = $request->input('status');
        $reports = $this->reportService->getReportsList($status, 20);

        return Inertia::render('Admin/Reports', [
            'reports' => $reports,
            'filters' => [
                'status' => $status,
            ],
            'pendingCount' => $this->adminService->getPendingReportsCount(),
        ]);
    }

    /**
     * 处理举报
     */
    public function processReport(Request $request, Report $report)
    {
        $request->validate([
            'status' => ['required', 'in:resolved,rejected'],
            'action' => ['nullable', 'in:delete,warn,no_action'],
            'admin_comment' => ['nullable', 'string', 'max:500'],
        ]);

        try {
            $this->adminService->processReport($report, $request->user(), $request->only([
                'status',
                'action',
                'admin_comment',
            ]));

            return redirect()->back()->with('success', '举报已处理');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
